<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户偏好设置</span>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleInit">初始化偏好</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="preferencesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="旅行风格" align="center" prop="travelStyle" />
        <el-table-column label="预算范围" align="center" prop="budgetRange" />
        <el-table-column label="住宿偏好" align="center" prop="accommodationType" />
        <el-table-column label="交通偏好" align="center" prop="transportPreference" />
        <el-table-column label="美食偏好" align="center" prop="foodPreference" />
        <el-table-column label="旅行伙伴" align="center" prop="travelCompanions" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 偏好设置对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" :disabled="dialogType !== 'add'" />
        </el-form-item>
        <el-form-item label="旅行风格" prop="travelStyle">
          <el-select v-model="form.travelStyle" placeholder="请选择旅行风格" clearable>
            <el-option label="冒险" value="adventure"></el-option>
            <el-option label="休闲" value="leisure"></el-option>
            <el-option label="文化" value="cultural"></el-option>
            <el-option label="美食" value="food"></el-option>
            <el-option label="购物" value="shopping"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预算范围" prop="budgetRange">
          <el-select v-model="form.budgetRange" placeholder="请选择预算范围" clearable>
            <el-option label="预算型" value="budget"></el-option>
            <el-option label="中等" value="medium"></el-option>
            <el-option label="豪华型" value="luxury"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="住宿偏好" prop="accommodationType">
          <el-select v-model="form.accommodationType" placeholder="请选择住宿偏好" clearable>
            <el-option label="酒店" value="hotel"></el-option>
            <el-option label="青年旅社" value="hostel"></el-option>
            <el-option label="民宿" value="bnb"></el-option>
            <el-option label="度假村" value="resort"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交通偏好" prop="transportPreference">
          <el-select v-model="form.transportPreference" placeholder="请选择交通偏好" clearable>
            <el-option label="飞机" value="flight"></el-option>
            <el-option label="火车" value="train"></el-option>
            <el-option label="公交" value="bus"></el-option>
            <el-option label="自驾" value="car"></el-option>
            <el-option label="骑行" value="bike"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="美食偏好" prop="foodPreference">
          <el-select v-model="form.foodPreference" placeholder="请选择美食偏好" clearable>
            <el-option label="本地菜" value="local"></el-option>
            <el-option label="国际菜" value="international"></el-option>
            <el-option label="素食" value="vegetarian"></el-option>
            <el-option label="清真菜" value="halal"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="旅行伙伴" prop="travelCompanions">
          <el-select v-model="form.travelCompanions" placeholder="请选择旅行伙伴" clearable>
            <el-option label="独自" value="solo"></el-option>
            <el-option label="情侣" value="couple"></el-option>
            <el-option label="家庭" value="family"></el-option>
            <el-option label="朋友" value="friends"></el-option>
            <el-option label="团体" value="group"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="兴趣标签" prop="interestTags">
          <el-input v-model="form.interestTags" type="textarea" placeholder="请输入兴趣标签，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="偏好城市" prop="preferredCities">
          <el-input v-model="form.preferredCities" type="textarea" placeholder="请输入偏好城市，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="避开城市" prop="avoidCities">
          <el-input v-model="form.avoidCities" type="textarea" placeholder="请输入避开城市，多个用逗号分隔" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, getByUserId, updateByUserId, initDefault } from "@/api/system/preferences";

export default {
  name: "UserPreferences",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 偏好设置表格数据
      preferencesList: [],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      open: false,
      // 弹出层类型（add: 新增, update: 修改, view: 查看）
      dialogType: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    // 检查路由参数中是否有userId
    const userId = this.$route.query.userId;
    if (userId) {
      this.queryParams.userId = userId;
    }
    this.getList();
  },
  methods: {
    /** 查询偏好设置列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        this.preferencesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 初始化偏好按钮操作 */
    handleInit() {
      this.open = true;
      this.dialogTitle = "初始化用户偏好";
      this.dialogType = "add";
      this.form = {
        userId: undefined,
        travelStyle: undefined,
        budgetRange: undefined,
        accommodationType: undefined,
        transportPreference: undefined,
        foodPreference: undefined,
        travelCompanions: undefined,
        interestTags: undefined,
        preferredCities: undefined,
        avoidCities: undefined
      };
    },
    /** 查看按钮操作 */
    handleView(row) {
      getByUserId(row.userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.dialogTitle = "偏好设置详情";
        this.dialogType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getByUserId(row.userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.dialogTitle = "修改偏好设置";
        this.dialogType = "update";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.dialogType === "add") {
            // 初始化默认偏好设置
            initDefault(this.form.userId).then(response => {
              this.$modal.msgSuccess("初始化成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.$modal.msgError("初始化失败");
            });
          } else if (this.dialogType === "update") {
            // 处理JSON字段
            const formData = { ...this.form };
            if (formData.interestTags && typeof formData.interestTags === 'string') {
              formData.interestTags = formData.interestTags.split(',').map(tag => tag.trim()).filter(tag => tag);
            }
            if (formData.preferredCities && typeof formData.preferredCities === 'string') {
              formData.preferredCities = formData.preferredCities.split(',').map(city => city.trim()).filter(city => city);
            }
            if (formData.avoidCities && typeof formData.avoidCities === 'string') {
              formData.avoidCities = formData.avoidCities.split(',').map(city => city.trim()).filter(city => city);
            }
            
            updateByUserId(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.$modal.msgError("修改失败");
            });
          } else {
            this.open = false;
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.resetForm("form");
    }
  }
};
</script>